﻿using System;
using System.Collections.ObjectModel;
using System.ComponentModel.Composition;
using System.Reflection;

namespace OperationPlugins.Proxies.CodeDom.CustomAttributeTypedArgumentValueParsers
{
    /// <summary>
    /// Parses Boolean values from CustomAttributeTypedArgument objects.
    /// </summary>
    [Export(typeof(ICustomAttributeTypedArgumentValueParser))]
    internal sealed class BooleanParser : ICustomAttributeTypedArgumentValueParser
    {
        bool ICustomAttributeTypedArgumentValueParser.TryParse(CustomAttributeTypedArgument arg, out string value)
        {
            value = null;

            if (arg.ArgumentType == typeof(Boolean[]))
            {
                var items = (ReadOnlyCollection<CustomAttributeTypedArgument>)arg.Value;

                value = string.Format("new System.Boolean[{0}] {{ ", items.Count);

                for (int i = 0; i < items.Count; i++)
                {
                    var item = (Boolean)items[i].Value;
                    var v = Parse(item);

                    if (i == 0)
                    {
                        value = string.Format("{0} {1}", value, v);
                    }
                    else
                    {
                        value = string.Format("{0}, {1}", value, v);
                    }
                }

                value = string.Format("{0} }}", value);

                return true;
            }

            if (arg.ArgumentType == typeof(Boolean))
            {
                value = Parse((Boolean)arg.Value);
                return true;
            }

            return false;
        }

        private static string Parse(Boolean v)
        {
            string value = (v) ? "true" : "false";
            return value;
        }

    }
}
